<script setup>
import { nextTick, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import PlayVideo from '@/components/PlayVideo.vue'
import ConnectedGame from '@/components/ConnectedGame.vue'
import GeneralButton from '@/components/GeneralButton.vue'
import showMsg from '@/utils/showMsg'
import { removeLogin } from '@/utils/auth'
import formatDate from '@/utils/formatDate'
import showCoin from '@/utils/showCoin'
import BackgroundImage from '@/components/BackgroundImage.vue'

const router = useRouter()
const fraction = ref(0)
const type = ref('video')
const count = ref(1)
const videoUrl = ref('')
const questions = ref([])
const dialogueId = ref()
const startTime = ref()
const endTime = ref()
const connections = ref([])

const submit = async () => {
  endTime.value = formatDate(new Date())
  try {
    console.warn('------------------')
    console.log(startTime.value)
    console.log(endTime.value)
    console.log(connections.value)
    console.log(dialogueId.value)
    console.warn('------------------')
    // 获取一下 connections 里面正确的数量
    // 正确的数量
    let correctCount = 0
    // 所得积分，正确加一分，错误减一分，最少为 0
    let currentScore = 0
    if (connections.value.length !== 0) {
      connections.value.map((item) => {
        const { sourceId, targetId } = item
        if (
          ((sourceId === '0' || sourceId === 'locomotive') &&
            (targetId === 'locomotive' || targetId === '0')) ||
          ((sourceId === '1' || sourceId === 'fuel') &&
            (targetId === 'fuel' || targetId === '1')) ||
          ((sourceId === '2' || sourceId === 'wagon') &&
            (targetId === 'wagon' || targetId === '2')) ||
          ((sourceId === '3' || sourceId === 'converter') &&
            (targetId === 'converter' || targetId === '3')) ||
          ((sourceId === '4' || sourceId === 'tail') && (targetId === 'tail' || targetId === '4'))
        ) {
          // 连线正确，加一分，并且记录正确的数量
          correctCount++
          currentScore++
          console.log(true)
        } else {
          // 连线错误，扣一分
          currentScore = Math.max(0, currentScore - 1)
          console.log(false)
        }
      })
    }
    console.warn('------------------')
    // 请求添加游戏记录
    const response = await axios.post(
      '/api/north/record',
      {
        part: 1,
        fraction: parseInt(fraction.value),
        rightNum: parseInt(correctCount),
        allNum: 5,
        dialogueId: dialogueId.value,
        beginTime: startTime.value,
        endTime: endTime.value
      },
      {
        headers: {
          Authorization: localStorage.getItem('token')
        }
      }
    )
    if (fraction.value > 0) {
      showCoin({ count: fraction.value })
    }
    console.log(response.data)
  } catch (e) {
    console.log(e)
  }
}

const fetchNewVideo = async () => {
  try {
    const response = await axios.get('/api/north/video', {
      headers: {
        Authorization: localStorage.getItem('token')
      }
    })
    console.log(response)
    const { code } = response.data
    if (code === 401) {
      showMsg({
        type: 'error',
        msg: '登录过期，请重新登录',
        duration: 1000,
        onClose: () => {
          removeLogin()
          router.push({ name: 'login' })
        }
      })
    } else if (code === 200) {
      const { data } = response.data
      console.log(data)
      if (!data) {
        router.push({ name: 'game-select' })
      } else {
        startTime.value = formatDate(new Date())
        console.log(startTime.value)
        videoUrl.value = data.path
        dialogueId.value = data.ques[0].dialogueId
        console.log('dialogueId', dialogueId.value)
        questions.value = data.ques
        questions.value = questions.value.map((question) => {
          return {
            ...question,
            stem: question.stem
              .split('\n')
              .map((line) => line.replace(/\?/g, '？').replace(/!/g, '！'))
          }
        })
      }
    } else throw new Error()
  } catch (e) {
    console.log(e)
    showMsg({
      type: 'error',
      msg: '网络错误，请稍后重试',
      duration: 1000,
      onClose: () => {
        router.push({ name: 'game-select' })
      }
    })
  }
}

const next = async () => {
  if (type.value === 'game') {
    type.value = 'video'
    // 获取新的视频
    await nextTick()
    await submit()
    await fetchNewVideo()
  } else {
    type.value = 'game'
  }
  fraction.value = 0
  count.value++
}

onMounted(async () => {
  await fetchNewVideo()
})
</script>
<template>
  <div class="background">
    <background-image />
    <play-video v-if="type === 'video'" style="flex: 1" :videoUrl="videoUrl" />
    <connected-game
      v-else-if="type === 'game'"
      style="flex: 1"
      :questions="questions"
      v-model:connections="connections"
      v-model:fraction="fraction"
    />
    <general-button
      style="left: 50%; transform: translate(-50%, 0); width: fit-content"
      @click="next"
      >下一个</general-button
    >
  </div>
</template>
<style scoped>
.background {
  background: -webkit-linear-gradient(#79bcff, #e7f7ff 100%);
  background: -moz-linear-gradient(#79bcff, #e7f7ff 100%);
  background: -o-linear-gradient(#79bcff, #e7f7ff 100%);
  background: -ms-linear-gradient(#79bcff, #e7f7ff 100%);
  background: linear-gradient(#79bcff, #e7f7ff 100%);
  height: 100vh;
  margin: auto;
  overflow: hidden;
  position: relative;
  display: flex;
  flex-direction: column;
  padding: 64px 40px;
}
</style>
